<template>
    <div class="container">
        <div class="handle-box">
            <el-form ref="form" :model="form" label-width="90px" class="flex">
                <el-form-item label="地区：" class="wid33">
                    <el-select
                        v-model="searchForm.REGION_ID"
                        placeholder="请选择地区"
                        @change="changeStreet"
                    >
                        <el-option
                            v-for="item in clientNameOpts"
                            :key="item.REGION_ID"
                            :label="item.REGION_NAME"
                            :value="item.REGION_ID"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="街道：" class="wid33">
                    <el-select
                        v-model="searchForm.STREET_ID"
                        placeholder="请选择街道"
                        @change="changeCommunity"
                        clearable
                    >
                        <el-option
                            v-for="item in streetOpts"
                            :key="item.STREET_ID"
                            :label="item.STREET_NAME"
                            :value="item.STREET_ID"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="社区：" class="wid33">
                    <el-select
                        v-model="searchForm.COMMUNITY_ID"
                        placeholder="请选择"
                        @change="changePlot"
                        clearable
                    >
                        <el-option
                            v-for="item in communityOpts"
                            :key="item.COMMUNITY_ID"
                            :label="item.COMMUNITY_NAME"
                            :value="item.COMMUNITY_ID"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="小区：" class="wid33">
                    <el-select v-model="searchForm.VILLAGE_ID" placeholder="请选择" clearable>
                        <el-option
                            v-for="item in plotOpts"
                            :key="item.VILLAGE_ID"
                            :label="item.VILLAGE_NAME"
                            :value="item.VILLAGE_ID"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="日期范围：">
                    <el-date-picker
                        v-model="dateRange"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd"
                        :clearable="false"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="mohu()">搜索</el-button>
                    <el-button style="padding:0;border:0">
                        <el-upload
                            action="/上传文件的接口"
                            :on-change="onChange"
                            :auto-upload="false"
                            :show-file-list="false"
                            accept=".xls, .xlsx"
                            class="upload"
                        >
                            <el-button
                                type="warning"
                                icon="el-icon-folder-add"
                                style="width:97px;height:33px"
                            >导入列表</el-button>
                        </el-upload>
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-table :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)">
            <el-table-column prop="VID" label="ID" width="55" align="center"></el-table-column>
            <el-table-column prop="STREET_NAME" label="所属街道"></el-table-column>
            <el-table-column prop="COMMUNITY_NAME" label="所属社区"></el-table-column>
            <el-table-column prop="VILLAGE_NAME" label="所属小区"></el-table-column>
            <el-table-column prop="NAME" label="居民姓名"></el-table-column>
            <el-table-column prop="TIME" label="日期范围"></el-table-column>
            <el-table-column prop="Recyclable" label="可回收垃圾累计称重(kg)"></el-table-column>
            <el-table-column prop="Kitchen" label="厨余收垃圾累计称重(kg)"></el-table-column>
            <el-table-column prop="Harmful" label="有害收垃圾累计称重(kg)"></el-table-column>
            <el-table-column prop="Other" label="其他收垃圾累计称重(kg)"></el-table-column>
            <el-table-column prop="sumAmount" label="总称重(kg)">
                <template
                    slot-scope="scope"
                >{{(scope.row.Recyclable + scope.row.Kitchen + scope.row.Harmful + scope.row.Other)}}</template>
            </el-table-column>
            <el-table-column prop="integral" label="积分">0</el-table-column>
            <el-table-column label="操作" width="180" align="center">
                <template slot-scope="scope">
                    <el-button
                        type="text"
                        icon="el-icon-edit"
                        @click="handleEdit(scope.$index, scope.row)"
                    >查看</el-button>|
                    <el-button
                        type="text"
                        @click="detail(scope.$index, scope.row)"
                        style="color:blue"
                    >垃圾投放明细</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :current-page="currentPage"
                :page-size="pagesize"
                :total="tableData.length"
                @size-change="handleSizeChange"
                @current-change="handlePageChange"
            ></el-pagination>
        </div>
        <!-- 编辑弹出框 -->
        <el-dialog
            v-dialogDrag
            title="居民统计详情"
            :visible.sync="editVisible"
            width="30%"
            style="padding-top:10px;font-weight:600"
        >
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane v-for="item in ljtype" :name="item.TYPE_ID" :label="item.TYPE_NAME">
                    <!-- {{item}} -->
                    <!-- <template slot-scope="scope">
                        <el-form ref="form" :model="form" label-width="100px" v-for="items in garbage">
                            <el-form-item :label="items.RUBBISH_NAME">
                                <el-input v-model="items.WEIGHT" readonly="true">kg</el-input>
                            </el-form-item>
                        </el-form>
                    </template>-->
                    <el-form ref="form" :model="form" label-width="100px" v-for="items in garbage">
                        <el-form-item :label="items.RUBBISH_NAME">
                            <el-input v-model="items.WEIGHT" readonly="true">kg</el-input>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </el-dialog>
        <!-- 积分明细 -->
        <el-dialog v-dialogDrag title="投放明细" :visible.sync="detaildialog" width="35%">
            <el-table :data="detaildata" height="250" border style="width: 100%">
                <el-table-column prop="WEIGHT_TIME" label="投放日期：" width="180"></el-table-column>
                <el-table-column prop="TYPE_NAME" label="投放垃圾类型：" width="180">
                    <!-- <template scope="scope">
                            <div class="u" @click="gettonnagelx()">{{ scope.row.TYPE_NAME }}</div>
                    </template>-->
                </el-table-column>
                <el-table-column prop="WEIGHT" label="投放公斤数：">
                    <!-- <template scope="scope">
                            <div class="u" @click="gettonnage()">{{ scope.row.tonnage }}</div>
                    </template>-->
                </el-table-column>
            </el-table>
        </el-dialog>
        <el-dialog v-dialogDrag title="投放明细" :visible.sync="gettonnagelxdialog" width="30%">
            <el-table :data="gettonnagelxdata" height="250" border style="width: 100%">
                <el-table-column prop="type" label="投放物品：" width="180"></el-table-column>
                <el-table-column prop="tonnage" label="投放公斤数：" width="180"></el-table-column>
                <!-- <el-table-column
                      prop="tonnage"
                      label="投放公斤数：">
                         <template scope="scope">
                            <div class="u" @click="gettonnage()">{{ scope.row.tonnage }}</div>
                        </template>
                </el-table-column>-->
            </el-table>
        </el-dialog>
    </div>
</template>
<script>
import '../../assets/css/common.css'

export default {
  data () {
    return {
      inputExcelDataIndex:0,
      inputExcelDataLength:0,
      fullscreenLoading: false,
      strError: '',
      currentPage: 1, //初始页
      pagesize: 10,    //    每页的数据
      userList: [],
      address: '',
      name: '',
      dateRange: [],
      activeName: 1,
      detaildialog: false,
      gettonnagelxdata: [{
        type: '纸张',
        tonnage: '5'
      }, {
        type: '塑料',
        tonnage: '5'
      }, {
        type: '硬纸板',
        tonnage: '5'
      }, {
        type: '纸张',
        tonnage: '5'
      }, {
        type: '纸张',
        tonnage: '5'
      }, {
        type: '纸张',
        tonnage: '5'
      },],
      searchForm: {
        REGION_ID: '',
        STREET_ID: '',
        COMMUNITY_ID: '',
        VILLAGE_ID: ''
      },
      clientNameOpts: [],
      streetOpts: [],
      communityOpts: [],
      plotOpts: [],
      tableData: [],
      multipleSelection: [],
      delList: [],
      editVisible: false,
      pageTotal: 0,
      form: {},
      idx: -1,
      id: -1,
      ljtype: '',
      detaildata: [{
        data: '2020-7-01',
        toufangleix: '可回收垃圾',
        tonnage: '20'
      }, {
        data: '2020-7-02',
        toufangleix: '不回收垃圾',
        tonnage: '20'
      }, {
        data: '2020-7-03',
        toufangleix: '厨余垃圾',
        tonnage: '20'
      }, {
        data: '2020-7-05',
        toufangleix: '有害垃圾',
        tonnage: '20'
      }, {
        data: '2020-7-08',
        toufangleix: '有害垃圾',
        tonnage: '20'
      }, {
        data: '2020-7-10',
        toufangleix: '有害垃圾',
        tonnage: '20'
      }, {
        data: '2020-7-15',
        toufangleix: '厨余垃圾',
        tonnage: '20'
      },],
      gettonnagelxdialog: false,
      rowbobject: '',
      garbage: ''
    }
  },
  computed: {
  },
  async created () {
    const startTime = this.$moment().subtract(1, 'months').format('YYYY-MM-DD');
    const endTime = this.$moment().add(0, 'day').format('YYYY-MM-DD');
    this.dateRange = [startTime, endTime];
    await this.getClientNameOpts();
    this.getdata();
    this.gettype();
    this.getljtype()
  },
  methods: {
    // 获取行政区
    async getClientNameOpts () {
      const { data } = await this.$axios.get(`${this.$url}/GetRegionListApi`);
      this.clientNameOpts = data;
      if (localStorage.getItem('clentno')) {
        this.searchForm.REGION_ID = localStorage.getItem('clentno');
        this.changeStreet(this.searchForm.REGION_ID);
      } else {
        this.searchForm.REGION_ID = data[0].REGION_ID;
        this.changeStreet(this.searchForm.REGION_ID);
        if (localStorage.getItem('STREET_NO') && localStorage.getItem('STREET_NO') !== 'null') {
          this.searchForm.STREET_ID = localStorage.getItem('STREET_NO');
          this.changeCommunity(this.searchForm.STREET_ID);
        }
      }
    },
    // 获取街道
    async changeStreet (val) {
      const { data } = await this.$axios.get(`${this.$url}/sreetListsApi?id=${val}`);
      this.streetOpts = data;
    },
    // 获取社区
    async changeCommunity (val) {
      const { data } = await this.$axios.get(`${this.$url}/communityListsApi?id=${val}`);
      this.communityOpts = data;
    },
    // 获取小区
    async changePlot (val) {
      const { data } = await this.$axios.get(`${this.$url}/villageListsApi?id=${val}`);
      this.plotOpts = data;
    },
    handleClick (tab, event) {
      // console.log(tab,event)
      // console.log(this.rowbobject)
      // console.log(event.target.getAttribute('id').split('-')[1])
      this.$axios({
        url: this.$surl + '/GetResidentGarbageCollectionDetailApi',
        method: 'get',
        params: {
          startTime: this.dateRange[0],
          endTime: this.dateRange[1],
          VID: this.rowbobject.VID,
          TYPE_ID: this.activeName
        }
      }).then(item => {
        this.garbage = Object.assign([], item.data)
      })
      // this.typeid= event.target.getAttribute('id').split('-')[1]
    },
    getljtype () {
      this.$axios({
        url: this.$url + '/GetRubbishTypeApi',
        method: 'get'
      }).then(item => {
        // console.log(this.TYPE_ID)
        this.ljtype = Object.assign([], item.data)
      })
    },
    gettonnagelx () {
      this.gettonnagelxdialog = true
    },
    detail (index, row) {
      const startTime = this.dateRange[0];
      const endTime = this.dateRange[1];
      this.$axios({
        url: this.$surl + '/GetResidentLaunchDetailApi',
        method: 'get',
        params: {
          startTime,
          endTime,
          VID: row.VID
        }
      }).then(item => {
        this.detaildata = Object.assign([], item.data)
        console.log(item)
      })
      console.log(index, row)
      this.detaildialog = true
    },
    getdata () {
      let clientNo = '';
      let level = '';
      if (this.searchForm.VILLAGE_ID) {
        level = '小区';
        clientNo = this.searchForm.VILLAGE_ID;
      } else if (this.searchForm.COMMUNITY_ID) {
        level = '社区';
        clientNo = this.searchForm.COMMUNITY_ID;
      } else if (this.searchForm.STREET_ID) {
        level = '街道';
        clientNo = this.searchForm.STREET_ID;
      } else if (this.searchForm.REGION_ID) {
        level = '行政区';
        clientNo = this.searchForm.REGION_ID;
      }
      let that = this
      const startTime = this.dateRange[0];
      const endTime = this.dateRange[1];
      // const ClientNo = localStorage.getItem('clentno');
      // const ClientNo = '002';
      that.$axios({
        url: `${this.$surl}/GetResidentGarbageCollectionApi`,
        method: 'get',
        params: {
          startTime,
          endTime,
          ClientNo: clientNo,
          Level: level
        }
      }).then(item => {
        this.tableData = Object.assign([], item.data)
        // this.tableData = item.data                                              
        // var totalscore = item.data.Recyclable+item.data.Other+item.data.Kitchen+item.data.Harmful
        // // this.tableData.push(totalscore)
        // console.log(totalscore)
        console.log(this.tableData)
        //    this.tableData.totalscore = isnumber(item.data.Recyclable)+isnumber(item.data.Other)+isnumber(item.data.Kitchen)+isnumber(item.data.Harmful)
      })
      // console.log(data)
    },
    mohu () {
      this.getdata();
    },
    // 编辑操作
    handleEdit (index, row) {
      this.rowbobject = Object.assign([], row)
      this.idx = index;
      this.form = row;
      this.editVisible = true;
      this.handleClick()
    },
    // 保存编辑
    // saveEdit() {
    //     this.editVisible = false;
    //     this.$message.success(`修改第 ${this.idx + 1} 行成功`);
    //     this.$set(this.tableData, this.idx, this.form);
    // },
    // 分页导航
    handlePageChange (currentPage) {
      this.currentPage = currentPage;
      console.log(this.currentPage)
      // this.$set(this.query, 'pageIndex', val);
      // this.getData();
    },
    handleSizeChange (size) {
      this.pagesize = size;
      console.log(this.pagesize)
    },
    async gettype () {
      const { data } = await this.$axios.get(this.$url + '/GetRubbishTypeApi');
      // console.log(data)
    },
    onChange (file, fileList) {
      //  console.log(fileList);
      this.fileData = file; // 保存当前选择文件
      this.readExcel(); // 调用读取数据的方法
    },
    // 读取数据
    readExcel (e) {
      let that = this;
      const files = that.fileData;
      console.log(files);
      if (!files) {
        //如果没有文件
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      const fileReader = new FileReader();
      console.log(fileReader)
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          //  console.log(ev.target)
          //  console.log(this);
          const workbook = this.XLSX.read(data, {
            type: "binary"
          });
          if (workbook.SheetNames.length >= 1) {
            //  this.$message({
            //    message: "导入数据表格成功",
            //    showClose: true,
            //    type: "success"
            //  });

            const wsname = workbook.SheetNames[0]; //取第一张表
            const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
            console.log(ws)
            this.inputExcelDataLength = ws.length
            this.fullscreenLoading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            for (let i = 0, len = ws.length; i < len; i++) {
              var item = ws[i]
              //   var sheetData = {
              //     VID: item['居民电话'],
              //     RUBBISH_NAME: item["垃圾品名"],
              //     WEIGHT: item["垃圾称重"],
              //     photo: '',
              //     LONGITUDE: 0,
              //     LATITUDE: 0
              //   }
              //   let exceldata =  []
              //   exceldata.push(sheetData)
              this.addWeight(item)
            }
          } else {
            this.$message.error("未读取到表格内容");
          }
        } catch (e) {
          return false;
        }
      };
      // 如果为原生 input 则应是 files[0]
      fileReader.readAsBinaryString(files.raw);
    },
    async addWeight (item) {
      //   ws.filter(item => {
      var strPara = '[{"NAME":' + item['居民名称'] + ',"TYPE_ID":0,"RUBBISH_NAME":"' + item["垃圾品名"] + '","WEIGHT":' + item["垃圾称重"] + '","IDCARD":' + item["垃圾点位名称"] + ',"photo":"","LONGITUDE":0,"LATITUDE":0}]'
      this.$axios({
        url: this.$aurl + '/AddWeightWithPhoneApi',
        method: 'get',
        params: { JsonStr: strPara }
      }).then(res => {
        console.log(res)
        this.inputExcelDataIndex++
        if (res.data.IsSucess) {
          
        } else {
          this.strError += this.inputExcelDataIndex + "行"
        }
        if (this.inputExcelDataIndex == this.inputExcelDataLength) {
          this.fullscreenLoading.close()
          if (this.strError.length == 0) {
            this.$message.success('表格文件导入成功')
          } else {
            this.$message.error('表格文件导入结束，' + this.strError + "未导入");
          }
          this.getdata()
        }
      })
      //   })
    }
  }
}
</script>
<style scoped>
/deep/.el-upload__input {
    display: none !important;
}
/deep/.el-upload__input {
    display: none;
}
/deep/.el-form-item .el-form-item__content {
    display: flex;
}
</style>